<template>
	<section class="wrapper">
		<div class="my_file">
			<p class="file_title">{{$t('title_text.cloud_disk_menu_title')}}</p>
			<el-menu :default-active="state.classify_index" class="el-menu-vertical-demo">
				<el-menu-item v-for="item in state.files_classify" :index="item.cat_value" :key="item.cat_value"
					@click="handleOpen(item.cat_value)">
					<span>{{item.classify_name}}</span>
				</el-menu-item>
			</el-menu>
			<div class="space_box">
				<p><span style="font-weight: 900;">{{$t('other_text.cloud_storage_space')}}:</span>{{$t('other_text.have_already_used')}} {{state.User_Cloud_disk_size}} / 5GB</p>
				<div class="progress_box">
					<el-progress :percentage="state.percentage" :color="state.customColors" :show-text="false"
						:stroke-width="8" />
				</div>
				<el-button color="#1890ff" style="padding: 0 50px;">{{$t('other_text.expand_storage_space')}}</el-button>
			</div>
		</div>
		<div class="files_box">
			<div class="top_funs">
				<div class="funs_left">
					<el-checkbox :label="$t('check_text.check_all')" v-model="state.all_checked"
						@change="Change_all_check" />
					<span @click="Delete_file"
						:style="{color:state.chenk_true_list.length>0?'#333':'#999',cursor:state.chenk_true_list.length>0?'pointer':'not-allowed'}"><el-icon>
							<Delete />
						</el-icon> {{$t('button.delete_btn')}}</span>
					<span @click="Rename_file"
						:style="{color:state.chenk_true_list.length>0?'#333':'#999',cursor:state.chenk_true_list.length>0?'pointer':'not-allowed'}"><el-icon>
							<Edit />
						</el-icon> {{$t('button.rechristen')}}</span>
					<span @click="Download_file"
						:style="{color:state.chenk_true_list.length>0?'#333':'#999',cursor:state.chenk_true_list.length>0?'pointer':'not-allowed'}"><el-icon>
							<Download />
						</el-icon> {{$t('button.download')}}</span>
				</div>
				<div style="display: flex;">
					<el-upload :action="store.state.request_url+'/api/v1/material/upload'" multiple
						:headers="state.headers" :on-success="handleAvatarSuccess" :on-progress="handleAvatarprogress"
						:before-upload="uplandfile" :on-error="handleAvatarerror" :show-file-list="false">
						<el-button color="#169bd5" :icon="Upload"> {{$t('button.Upload_files_to_cloud')}}</el-button>
					</el-upload>&emsp;
					<el-button color="#169bd5" :icon="UploadFilled" @click="clouds_show">
						{{$t('button.transfer_cloud')}}</el-button>
				</div>
			</div>
			<el-upload class="upload-demo" drag :action="store.state.request_url+'/api/v1/material/upload'" multiple
				:headers="state.headers" :on-success="handleAvatarSuccess" :on-progress="handleAvatarprogress"
				:before-upload="uplandfile" :on-error="handleAvatarerror" :show-file-list="false" @click.native.stop>
				<div class="files_list_box">
					<div v-for="item in state.check_File_list" :key="item.name"
						@click.stop="handleItemClick($event,item)">
						<el-checkbox class="top_check" v-model="item.checked" @change="updateCheckedById(item)" />
						<el-popover class="box-item" placement="bottom" :content="item.name">
							<template #reference>
								<el-icon :size="50" :color="item.checked?'#1890ff':'#2c3e50'">
									<Document />
								</el-icon>
							</template>
						</el-popover>
						<p style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap">{{item.name}}</p>
						<!-- <p style="font-weight: 900;">{{formatFileSize(item.size)}}</p> -->
					</div>
				</div>
			</el-upload>
		</div>
		<!-- 云手机列表弹框 -->
		<el-dialog v-model="state.Cloud_dialog_flag" title="选择云手机" width="500">
			<el-table :data="state.clouds_list" :header-cell-style="headerRowStyle"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column label="云机ID">
					<template #default="scope">
						<span>{{scope.row.instances.name}}</span>
					</template>
				</el-table-column>
				<el-table-column property="instance_name" label="云机名称" />
			</el-table>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="import_cloud_file">传输至云机</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 重命名文件弹框 -->
		<el-dialog v-model="state.Rename_dialog_flag" destroy-on-close :title="$t('title_text.cloud_disk_dialog_title')" width="1000">
			<div class="Rename_dialog_content_box">
				<div class="Rename_dialog_left_box">
					<div>
						<p style="color: #000;">{{$t('other_text.edit_file_name')}}</p>
						<div ref="editor" class="input_box" :class="{ 'editor-focus': isEditorFocused }"
							contenteditable="true" @focus="isEditorFocused = true" @blur="isEditorFocused = false"
							@keyup="handleKeyup" @keydown="handleKeydown" @cut="handleCut" @paste="handlePaste">
						</div>
					</div>
					<div>
						<p><el-checkbox :label="$t('check_text.insert_filename')" v-model="state.old_file_checked" @change="push_old_file_name" />
						</p>
						<p><el-checkbox :label="$t('check_text.insert_serial')" v-model="state.serial_checked" @change="serial_click" /></p>
					</div>
				</div>
				<div class="Rename_dialog_right_files">
					<div v-for="item in state.Rename_check_list" :key="item.name">
						<el-icon :size="50">
							<Document />
						</el-icon>
						<p>{{item.name}}</p>
					</div>
				</div>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="state.Rename_dialog_flag = false">{{$t('button.cancel')}}</el-button>
					<el-button type="primary" @click="Rename_Confirm">{{$t('button.confirm')}}</el-button>
				</div>
			</template>
		</el-dialog>
	</section>
</template>
<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted,
		onUnmounted,
		getCurrentInstance,
		watch,
		createVNode,
		render
	} from 'vue';
	import {
		Delete,
		Edit,
		Download,
		Upload,
		UploadFilled,
		Document,
	} from '@element-plus/icons-vue';
	import request from '@/utils'
	import {
		ElMessage,
		ElMessageBox,
		ElLoading,
		ElIcon
	} from 'element-plus';
	import {
		calcPercentOf5GB,
		formatFileSize,
		getProcessedName,
		name_splicing,
		jojn_inputandname,
		get_oldname_before,
		get_oldname_after
	} from '@/utils/computed_fun'
	import {
		useStore
	} from 'vuex';
	import axios from 'axios'
	import {
		useI18n
	} from 'vue-i18n'
	const {
		t
	} = useI18n()
	const store = useStore();
	const state = reactive({
		User_Cloud_disk_size: null, //用户云盘已占用的大小
		classify_index: '', // 分类菜单索引
		files_classify: computed(() => [{ //分类菜单数组
				classify_name: t('cloud_disk_menu.all'),
				cat_value: ''
			},
			{
				classify_name: t('cloud_disk_menu.apk'),
				cat_value: 'apk'
			},
			{
				classify_name: t('cloud_disk_menu.picture'),
				cat_value: 'image'
			},
			{
				classify_name: t('cloud_disk_menu.video'),
				cat_value: 'videos'
			},
			{
				classify_name: t('cloud_disk_menu.file'),
				cat_value: 'document'
			},
		]),
		percentage: 0,
		customColors: [{
				color: '#1890ff',
				percentage: 70
			},
			{
				color: '#f56c6c',
				percentage: 100
			},
		],
		all_checked: false,
		File_list: [], //文件数据原数组
		check_File_list: [], //添加特殊字段的数组(如checked选中字段)
		chenk_true_list: [], //所有选中的文件 数组
		Rename_check_list: [], //重命名文件
		clouds_list: [], //云手机表格列表数据
		checked_phone_list: [], //云手机表格列表选中返回的数据
		headers: { // 请求头部参数
			Authorization: `Bearer ${store.state.token} `
		},
		upload_loading: null, //上传文件中刷新
		Rename_dialog_flag: false, //重命名弹框开关
		old_file_checked: true, //插入原文件名的多选框
		serial_checked: false, //插入序号的多选框
		Cloud_dialog_flag: false, //云手机列表弹框开关
		backspaceTimeout: null,
		backspaceInterval: null
	});
	// 编辑器状态
	const editor = ref(null);
	const isEditorFocused = ref(false);
	/**
	 * 辅助函数：获取节点的前一个非空白兄弟节点（跳过空格、换行等空节点）
	 * @param {Node} node - 当前节点
	 * @returns {Node|null} - 前一个非空白兄弟节点
	 */
	const getPreviousNonEmptySibling = (node) => {
		let prevSibling = node.previousSibling;
		// 循环查找：跳过文本节点（仅含空格/换行）、注释节点
		while (prevSibling) {
			// 文本节点：判断是否仅含空白字符
			if (prevSibling.nodeType === Node.TEXT_NODE) {
				if (prevSibling.textContent.trim() !== '') {
					break; // 非空白文本节点，停止查找
				}
			}
			// 元素节点/其他有效节点：直接返回
			else if (prevSibling.nodeType === Node.ELEMENT_NODE) {
				return prevSibling;
			}
			// 继续查找上一个兄弟
			prevSibling = prevSibling.previousSibling;
		}
		return null;
	};
	// 检查选择范围是否包含受保护标签
	const selectionContainsProtectedTag = () => {
		const selection = window.getSelection();
		if (!selection.rangeCount) return null;

		const range = selection.getRangeAt(0);
		const protectedTags = editor.value?.querySelectorAll('[data-protected="true"]');
		if (!protectedTags || protectedTags.length === 0) return null;

		// 遍历所有保护标签，检测两种情况：
		for (const tag of protectedTags) {
			// 情况1：选区范围与标签直接相交（原有逻辑，覆盖光标在标签内/选中标签的场景）
			if (range.intersectsNode(tag)) {
				return tag;
			}

			// 情况2：选区在文本节点开头，且文本节点的前一个兄弟是保护标签（新增逻辑）
			const startContainer = range.startContainer;
			// 仅处理文本节点，且光标在文本开头（startOffset === 0）
			if (startContainer.nodeType === Node.TEXT_NODE && range.startOffset === 0) {
				// 获取文本节点的前一个非空白兄弟节点
				const prevSibling = getPreviousNonEmptySibling(startContainer);
				// 如果前兄弟是保护标签，返回该标签
				if (prevSibling === tag) {
					return tag;
				}
			}
		}
		return null;
	};
	// 处理删除操作
	const handleDelete = (e) => {
		const protectedTag = selectionContainsProtectedTag();
		if (protectedTag) {
			state.old_file_checked = false
			state.serial_checked = true
		}
	};
	//键盘删除事件
	function handleBackspace() {
		const inputBox = document.querySelector('.input_box');
		const datavalue = processNode(inputBox);
		const protectedTag = selectionContainsProtectedTag();
		console.log(protectedTag);
		if (protectedTag) {
			const protected_tag = document.querySelector('.protected-tag');
			protected_tag.remove(); // 清空内容
			var numbervalue = 0
			state.Rename_check_list.forEach((item, index) => {
				numbervalue++;
				state.Rename_check_list[index].name = getProcessedName(datavalue, item.name,
					numbervalue, false)
			})
			state.old_file_checked = false
			if (state.Rename_check_list.length > 1) {
				state.serial_checked = true
			}
		}
	}
	//监控粘贴事件
	const handlePaste = (e) => {
		// 1. 关键：阻止浏览器默认粘贴行为（避免解析富文本为HTML）
		e.preventDefault();
		// 2. 从剪贴板获取纯文本（忽略所有格式）
		// 兼容所有浏览器：e.clipboardData 或 window.clipboardData（IE）
		const clipboardData = e.clipboardData || window.clipboardData;
		const plainText = clipboardData.getData('text/plain') || ''; // 只取text/plain格式
		// 3. 将纯文本插入到当前光标位置（核心：不生成任何HTML元素）
		insertTextAtCursor(editor.value, plainText);
	};
	/**
	 * 工具函数：将纯文本插入到编辑框的当前光标位置
	 * @param {HTMLElement} editor - contenteditable元素
	 * @param {string} text - 要插入的纯文本
	 */
	const insertTextAtCursor = (editor, text) => {
		if (!editor || !text) return;

		// 获取当前选区（光标位置/选中的文本）
		const selection = document.getSelection();
		if (!selection) return;

		// 情况1：有选中的文本 → 先删除选中内容，再插入新文本
		if (selection.rangeCount > 0) {
			const range = selection.getRangeAt(0);
			range.deleteContents(); // 删除选中的内容

			// 创建纯文本节点（不是HTML元素，不会生成标签）
			const textNode = document.createTextNode(text);
			range.insertNode(textNode);

			// 调整光标位置到插入文本的末尾（优化体验）
			range.setStartAfter(textNode);
			range.setEndAfter(textNode);
			selection.removeAllRanges();
			selection.addRange(range);
		}
		// 情况2：无选中内容（光标在某个位置）→ 直接在光标处插入
		else {
			const textNode = document.createTextNode(text);
			editor.appendChild(textNode);
			// 调整光标到文本末尾
			const range = document.createRange();
			range.setStartAfter(textNode);
			range.setEndAfter(textNode);
			selection.removeAllRanges();
			selection.addRange(range);
		}
	};
	//键盘按下事件处理
	const handleKeydown = (e) => {
		if (e.key === 'Backspace') {
			// e.preventDefault(); // 阻止默认的删除行为
			// 清除之前的定时器
			if (state.backspaceInterval) {
				clearInterval(state.backspaceInterval);
			}
			if (state.backspaceTimeout) {
				clearTimeout(state.backspaceTimeout);
			}
			// 立即执行一次
			handleBackspace();
			// 设置延迟后开始连续执行
			state.backspaceTimeout = setTimeout(() => {
				state.backspaceInterval = setInterval(() => {
					handleBackspace();
				}, 100); // 每100毫秒执行一次
			}, 500); // 按住500毫秒后开始连续执行
		}
	}
	// 键盘松开事件处理
	const handleKeyup = (e) => {
		const inputBox = document.querySelector('.input_box');
		const datavalue = processNode(inputBox);
		// 处理删除键和退格键
		if (e.key === 'Delete') {
			handleDelete(e);
		} else {
			if (e.key === 'Backspace') {
				if (state.backspaceInterval) {
					clearInterval(state.backspaceInterval);
					state.backspaceInterval = null;
				}
				if (state.backspaceTimeout) {
					clearTimeout(state.backspaceTimeout);
					state.backspaceTimeout = null;
				}
			}
			if (state.serial_checked) {
				var numbervalue = 0
				state.Rename_check_list.forEach((item, index) => {
					numbervalue++;
					state.Rename_check_list[index].name = getProcessedName(datavalue, item.name,
						numbervalue, state.old_file_checked, item.old_name_nosuffix)
				})
			}
			if (state.old_file_checked) {
				var numbervalue = 0
				state.Rename_check_list.forEach((item, index) => {
					numbervalue++;
					state.Rename_check_list[index].name = name_splicing(datavalue, item.old_name,
						numbervalue, state.serial_checked)
				})
			}
			if (!state.old_file_checked && !state.serial_checked) {
				state.Rename_check_list.forEach((item, index) => {
					state.Rename_check_list[index].name = jojn_inputandname(datavalue, item.name)
				})
			}
		}
	};

	// 剪切事件处理
	const handleCut = (e) => {
		if (selectionContainsProtectedTag()) {
			state.old_file_checked = false
			state.serial_checked = true
		}
	};

	// 处理保护标签点击
	const handleProtectedTagClick = () => {
		// 将光标定位到标签后面
		setTimeout(() => {
			const selection = window.getSelection();
			const protectedTag = editor.value?.querySelector('[data-protected="true"]');
			if (protectedTag) {
				selection.removeAllRanges();
				const newRange = document.createRange();
				newRange.setStartAfter(protectedTag);
				newRange.setEndAfter(protectedTag);
				selection.addRange(newRange);
			}
		}, 0);
	};
	// 创建新标签元素
	const createNewTag = () => {
		// 创建外层容器
		const tagContainer = document.createElement('span');
		tagContainer.className = 'protected-tag';
		tagContainer.setAttribute('data-protected', 'true');
		const beforeSpace = document.createTextNode('\u00A0');
		const afterSpace = document.createTextNode('\u00A0');
		// 创建内部不可编辑元素
		const tagContent = document.createElement('span');
		tagContent.contentEditable = 'false';
		const iconVNode = createVNode(ElIcon, {}, {
			default: () => createVNode(Document)
		});
		// 关键：绑定当前应用的上下文（确保组件能正确解析）
		iconVNode.appContext = editor.value?._vnode?.appContext;
		// 创建文本节点
		const textNode = document.createTextNode('原文件名');
		// 创建一个临时容器用于挂载图标组件
		const iconContainer = document.createElement('span');
		tagContent.appendChild(beforeSpace);
		tagContent.appendChild(iconContainer);
		tagContent.appendChild(textNode);
		tagContent.appendChild(afterSpace);
		// 渲染图标组件到临时容器
		render(iconVNode, iconContainer);
		// 添加点击事件
		tagContent.addEventListener('mousedown', (e) => {
			e.preventDefault();
			handleProtectedTagClick(tagContainer);
		});
		tagContainer.appendChild(tagContent);
		// 【关键修改】始终添加到编辑器内容的末尾，忽略光标位置
		if (editor.value) {
			// 保存当前光标位置
			const selection = window.getSelection();
			const range = selection.rangeCount ? selection.getRangeAt(0) : null;
			// 将标签添加到编辑器末尾
			editor.value.appendChild(tagContainer);
			const inputBox = document.querySelector('.input_box');
			inputBox.appendChild(afterSpace);
			// 恢复光标位置（如果之前有选中范围）
			if (range) {
				selection.removeAllRanges();
				selection.addRange(range);
			}
		}
	};
	// 添加新标签功能
	const addNewTag = () => {
		if (!editor.value) return;
		// 创建新标签
		const newTag = createNewTag();
		// 获取当前选择位置
		const selection = window.getSelection();
		if (selection.rangeCount) {
			const range = selection.getRangeAt(0);
			range.insertNode(newTag);
			// 将光标移动到新标签后面
			range.setStartAfter(newTag);
			range.setEndAfter(newTag);
			selection.removeAllRanges();
			selection.addRange(range);
		} else {
			// 如果没有选择范围，添加到末尾
			editor.value.appendChild(newTag);
		}
	};
	// 递归处理节点，分割span前后的内容
	// 返回值：{ before: '', after: '', hasFoundSpan: false }
	const processNode = (node) => {
		// 初始化结果：before(span前内容)、after(span后内容)、hasFoundSpan(是否已遇到span)
		const result = {
			before: '',
			after: '',
			hasFoundSpan: false
		};
		// 1. 如果当前节点是span元素，标记已找到span，前后内容不变
		if (node.nodeType === Node.ELEMENT_NODE && node.tagName.toLowerCase() === 'span') {
			result.hasFoundSpan = true;
			return result;
		}
		// 2. 如果是文本节点，根据是否已找到span决定添加到before还是after
		if (node.nodeType === Node.TEXT_NODE) {
			result.before = node.textContent || '';
			return result;
		}
		// 3. 如果是其他元素节点，递归处理子节点
		if (node.childNodes && node.childNodes.length) {
			for (const child of node.childNodes) {
				const childResult = processNode(child);
				if (!result.hasFoundSpan) {
					if (!childResult.hasFoundSpan) {
						// 还没遇到span，累积before
						result.before += childResult.before;
					} else {
						result.before += childResult.before;
						result.after += childResult.after;
						result.hasFoundSpan = true; // 标记已找到span
					}
				} else {
					// 已经遇到过span，所有内容都算after
					result.after += childResult.before + childResult.after;
				}
			}
		}
		return result;
	};
	Get_Filedata()
	//获取文件数据
	function Get_Filedata() {
		const response = request.get(`/material/list?cat=${state.classify_index}`)
		response.then((res) => {
			const data = res.data.data.children ? res.data.data.children : []
			state.User_Cloud_disk_size = res.data.data.total_size
			state.percentage = calcPercentOf5GB(res.data.data.total_size)
			state.File_list = data
			state.all_checked = false
			state.chenk_true_list = []
			state.check_File_list = data.map(item => {
				return {
					...item,
					checked: false
				};
			});

		}).catch(() => {})
	}
	// 点击分类菜单项
	function handleOpen(key) {
		state.classify_index = key
		Get_Filedata()
	}
	//点击整体文件 逻辑方法(单选文件)
	function handleItemClick(event, file) {
		// 关键：判断点击的是否是复选框或其内部元素
		const isCheckbox = event.target.closest('.top_check, .el-checkbox');
		// 如果点击的是复选框，不执行任何操作（避免与change事件冲突）
		if (isCheckbox) {
			return;
		}
		// 点击的是其他区域（图标/文字等），才切换选中状态
		const Fileindex = state.check_File_list.findIndex(item => item.name == file.name);
		if (Fileindex || Fileindex == 0) {
			state.check_File_list[Fileindex].checked = !state.check_File_list[Fileindex].checked
		}
		// 同步更新选中列表等逻辑
		updateCheckedById(file);
	}
	//点击多选框的逻辑方法(单选方法)
	function updateCheckedById(file) {
		const Fileindex = state.check_File_list.findIndex(item => item.name == file.name);
		if (state.check_File_list[Fileindex].checked) {
			state.chenk_true_list.push(state.File_list[Fileindex])
		} else {
			const existsInA = state.chenk_true_list.findIndex(aItem => aItem.name == file.name);
			if (existsInA || existsInA == 0) {
				state.chenk_true_list.splice(existsInA, 1)
			}
		}
		const allChecked = state.check_File_list.every(item => item.checked);
		state.all_checked = allChecked;
	}
	//全选文件
	function Change_all_check(file) {
		const newarr = state.check_File_list.map(item => {
			return {
				...item,
				checked: state.all_checked
			};
		});
		state.check_File_list = newarr
		if (file) {
			state.chenk_true_list = state.File_list
		} else {
			state.chenk_true_list = []
		}
	}
	//重命名文件弹框(开启)
	function Rename_file() {
		// const hasCheckedTrue = state.check_File_list.some(item => item.checked === true);
		if (state.chenk_true_list.length > 0) {
			state.Rename_check_list = JSON.parse(JSON.stringify(state.chenk_true_list))
			// 为每个对象添加 old_name 属性，值等于当前的 name
			state.Rename_check_list = state.Rename_check_list.map(item => {
				return {
					...item,
					old_name: item.name, // 将当前 name 的值赋给 old_name
					old_name_nosuffix: get_oldname_before(item.name)
				};
			});
			if (state.Rename_check_list.length == 1) {
				state.old_file_checked = false
				state.serial_checked = false
			} else {
				setTimeout(() => {
					createNewTag();
					state.old_file_checked = true
					state.serial_checked = false
				}, 500)
			}
			state.Rename_dialog_flag = true
		}
	}
	//重命名文件弹框(确定)
	function Rename_Confirm() {
		const inputBox = document.querySelector('.input_box');
		const datavalue = processNode(inputBox);
		if (datavalue.before.trim() != '' || datavalue.after.trim() != '') {
			var oldNameS = []
			var NewNameS = []
			state.chenk_true_list.forEach((item, index) => {
				oldNameS.push(item.name)
			})
			state.Rename_check_list.forEach((item, index) => {
				NewNameS.push(item.name)
			})
			const response = request.post(`/material/rename`, {
				"oldName": oldNameS,
				"newName": NewNameS
			})
			response.then((res) => {
				if (res.data.code == 200) {
					Get_Filedata()
					ElMessage.success(res.data.data)
					state.Rename_dialog_flag = false
				}
			}).catch(() => {})
		} else {
			ElMessage.error('请输入新文件名')
		}
	}
	//插入序号
	function serial_click(checked) {
		const inputBox = document.querySelector('.input_box');
		const datavalue = processNode(inputBox);
		if (checked) {
			var numbervalue = 0
			state.Rename_check_list.forEach((item, index) => {
				numbervalue++;
				state.Rename_check_list[index]['serial'] = String(numbervalue).length
				state.Rename_check_list[index].name = getProcessedName(datavalue, item.name, numbervalue, state
					.old_file_checked, item.old_name_nosuffix)
			})
		} else {
			if (state.old_file_checked) {
				state.Rename_check_list.forEach((item, index) => {
					state.Rename_check_list[index].name = get_oldname_before(item.name).slice(0, String(item
						.serial).length * -1) + get_oldname_after(item.name)
				})
			} else {
				if (state.Rename_check_list.length > 1) {
					createNewTag()
					var numbervalue = 0
					state.Rename_check_list.forEach((item, index) => {
						numbervalue++;
						state.Rename_check_list[index].name = name_splicing(datavalue, item.old_name, numbervalue,
							checked)
					})
					state.old_file_checked = true
				} else {
					var numbervalue = 0
					state.Rename_check_list.forEach((item, index) => {
						numbervalue++;
						state.Rename_check_list[index].name = jojn_inputandname(datavalue, item.old_name)
					})
				}
			}
		}
	}
	//插入原文件名
	function push_old_file_name(checked) {
		const inputBox = document.querySelector('.input_box');
		const datavalue = processNode(inputBox);
		if (checked) {
			createNewTag()
			var numbervalue = 0
			state.Rename_check_list.forEach((item, index) => {
				numbervalue++;
				state.Rename_check_list[index]['serial'] = String(numbervalue).length
				state.Rename_check_list[index].name = name_splicing(datavalue, item.old_name, numbervalue, state
					.serial_checked)
			})
		} else {
			const protected_tag = document.querySelector('.protected-tag');
			protected_tag.remove(); // 清空内容
			if (state.Rename_check_list.length > 1) {
				state.serial_checked = true
			}
			if (state.Rename_check_list.length == 1 && !state.serial_checked) {
				var numbervalue = 0
				state.Rename_check_list.forEach((item, index) => {
					numbervalue++;
					state.Rename_check_list[index].name = jojn_inputandname(datavalue, item.old_name)
				})
			} else {
				var numbervalue = 0
				state.Rename_check_list.forEach((item, index) => {
					numbervalue++;
					state.Rename_check_list[index].name = getProcessedName(datavalue, item.name, numbervalue,
						checked)
				})
			}
		}
	}
	//云手机表格列表表头添加样式
	const headerRowStyle = ({
		row,
		rowIndex
	}) => {
		return {
			backgroundColor: '#f0f3f5', // 背景色
			color: '#212224', // 文字颜色
		};
	};
	//表格check选中返回数据
	function handleSelectionChange(val) {
		state.checked_phone_list = val
	}
	// 云手机弹框开关
	function clouds_show() {
		if (state.chenk_true_list.length > 0) {
			const response = request.get('/containers/list')
			response.then((res) => {
				state.clouds_list = res.data.data
				state.Cloud_dialog_flag = true
			}).catch(() => {})
		} else {
			ElMessage.warning('请先选择一个文件再传输')
		}
	}
	//传输文件至云机
	function import_cloud_file() {
		const file_nameS = []
		const Id_list = []
		state.chenk_true_list.forEach((item, index) => {
			file_nameS.push(item.name)
		})
		state.checked_phone_list.forEach((item, index) => {
			Id_list.push(item.id)
		})
		state.upload_loading = ElLoading.service({
			lock: true,
			text: '传输中,请等待...',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		const response = request.post('/material/transfer', {
			file_name: file_nameS,
			devices: Id_list
		})
		response.then((res) => {
			if (res.data.code == 200) {
				state.Cloud_dialog_flag = false
				state.upload_loading.close()
				ElMessage.success(res.data.data)
			}
		}).catch(() => {})
	}
	//下载文件
	function Download_file() {
		if (state.chenk_true_list.length > 0) {
			state.chenk_true_list.forEach((item, index) => {
				axios({
					url: 'https://clp.jtcloud.icu/api/v1/material/download?filename=' + item.name,
					method: 'get',
					headers: {
						'authorization': state.headers.Authorization
					},
					onDownloadProgress: p => {},
					responseType: 'blob'
				}).then(data => {
					if (data.status == 200) {
						// 由于ie不支持download属性，故需要做兼容判断
						if (navigator.appVersion.toString().indexOf('.NET') > 0) {
							// ie独有的msSaveBlob属性，data.data为Blob文件流
							window.navigator.msSaveBlob(data.data, fileName)
						} else {
							// 以下流程即为文章开始的下载流程
							let url = window.URL.createObjectURL(data.data)
							let link = document.createElement('a')
							link.style.display = 'none'
							link.href = url
							link.download = item.name
							document.body.appendChild(link)
							link.click()
							window.URL.revokeObjectURL(link.href);
						}
						ElMessage.success('下载成功')
					}
				}).catch(() => {})
			})
		}
	}
	//删除文件
	function Delete_file() {
		if (state.chenk_true_list.length > 0) {
			ElMessageBox.confirm('确定要删除所选中的文件吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
				.then(() => {
					var postdata = []
					state.chenk_true_list.forEach((item, index) => {
						postdata.push(item.name)
					})
					const response = request.post(`/material/delete`, {
						"name": postdata
					})
					response.then((res) => {
						if (res.data.code == 200) {
							Get_Filedata()
							ElMessage.success(res.data.data)
						}
					}).catch(() => {})
				})
				.catch(() => {
					// 用户取消，不执行 done()，对话框保持打开
					// console.log('用户取消关闭'); 
				});
		}
	}
	// 上传中的钩子
	function handleAvatarprogress(event, file, fileList) {
		state.upload_loading = ElLoading.service({
			lock: true,
			text: '上传中,请等待...',
			background: 'rgba(0, 0, 0, 0.7)',
		})
	}

	function handleAvatarerror(err, file, fileList) {
		// console.log(err);
		// console.log(file);
	}
	// 上传成功的钩子
	function handleAvatarSuccess(response, file, fileList) {
		if (response.code == 200) {
			state.upload_loading.close()
			Get_Filedata()
			ElMessage.success(response.data)
		}
		if (response.status == 500) {
			ElMessage.error('服务器出了点问题,上传失败,请稍后再试')
		}
	}
	//上传前对文件进行判断的钩子
	function uplandfile(file) {
		const sizedata = formatFileSize(file.size).slice(-2)
		if (sizedata == 'GB') {
			return false
		}
		if (sizedata == 'MB') {
			const matchResult = String(formatFileSize(file.size)).match(/\d+\.?\d*/)
			if (Number(matchResult) > 500) {
				ElMessage.error('上传单个文件最大不能超过500MB,请更换文件进行尝试')
				return false
			}
		}
	}
	onMounted(() => {
		// 获取内部的文件选择input元素
		const fileInput = document.querySelector('.upload-demo input[type="file"]');
		if (fileInput) {
			// 禁用input原生点击
			fileInput.disabled = true;
			// 移除所有事件监听器
			fileInput.replaceWith(fileInput.cloneNode(true));
			// 隐藏input
			fileInput.style.display = 'none';
		}
		//上述所以的目的都是为了禁止点击上传
	});
</script>

<style lang="less" scoped>
	.el-menu-vertical-demo .el-menu-item.is-active {
		background-color: #ddeefe !important;
	}

	.input_box {
		width: 60%;
		min-height: 100px;
		border-radius: 8px;
		border: 1px solid #dcdfe6;
		padding: 10px;
		text-align: left;
	}

	.input_box:focus {
		border: 1px solid #1890ff;
	}

	/deep/ .protected-tag {
		line-height: 100%;
		background-color: rgba(59, 130, 246, 0.1);
		color: #3B82F6;
		padding: 0.25rem 0.5rem;
		border-radius: 0.375rem;
		display: inline-block;
		margin: 0 0.25rem;
		border: 1px solid #6cb8ff;
		cursor: default;
		transition: all 0.2s;
	}

	.protected-tag:hover {
		background-color: rgba(59, 130, 246, 0.2);
	}

	.editor-focus {
		ring: 2px solid #6cb8ff;
		box-shadow: 0 0 0 1px rgba(59, 130, 246, 0.1);
	}

	.Rename_dialog_content_box {
		display: flex;
		align-items: start;

		.Rename_dialog_left_box {
			border-right: 1px solid #f5f5f5;
			padding: 0 20px;
			width: 40%;

			>div:nth-of-type(1) {
				margin-bottom: 60px;
				display: flex;
				align-items: flex-start;
				gap: 10px;

				span {
					display: inline-block;
					white-space: nowrap;
					// height: 100%;
				}
			}

			>div:nth-of-type(2) {
				text-align: left;
			}
		}

		.Rename_dialog_right_files {
			padding-left: 20px;
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;
			flex: 1;
			gap: 10px;

			div {
				width: 100px;
				min-width: 100px;
				max-width: 100px;
				padding: 10px;
				cursor: pointer;
			}
		}

		.Rename_dialog_right_files::after {
			content: "";
			flex: auto;
			/* 自动填充剩余空间，将最后一行元素向左推 */
		}
	}

	/deep/ .upload-demo {
		height: calc(100% - 80px);

		.el-upload {
			height: 100%;
		}

		.el-upload:focus {
			color: inherit;
		}

		.el-upload-dragger {
			height: 100%;
			border: none;
			cursor: default;
		}
	}

	.file_title {
		margin: 28px 0 28px 20px;
		text-align: center;
		color: #333;
		font-size: 16px;
		font-weight: 900;
	}

	.el-menu-vertical-demo {
		border-right: none;

		li {
			display: inline-block;
			width: 100%;
			text-align: center;
		}
	}

	/deep/ .el-checkbox__inner {
		border: 2px solid #6cb8ff;
	}

	// /deep/ .el-checkbox__inner:after {
	// 	// left: 3px;
	// 	// top: 45%;
	// }

	.wrapper {
		height: 100%;
		background-color: #fff;
		display: flex;
		flex-wrap: nowrap;
		border-radius: 10px;

		.my_file {
			width: 20%;
			border-right: 1px solid #e3e3e3;
			position: relative;

			.space_box {
				box-sizing: border-box;
				background-color: #ebf8fe;
				padding: 10px;
				border-radius: 5px;
				position: absolute;
				left: 20px;
				right: 20px;
				bottom: 20px;

				.progress_box {
					margin: 10px 0px;
				}

				.progress_box::before {
					content: '';
					width: 3px;
					height: 5px;
					background-color: #1890ff;
					position: absolute;
					right: 31%;
					bottom: 60px;
					z-index: 999;
				}

				.progress_box::after {
					content: '';
					width: 3px;
					height: 5px;
					background-color: #1890ff;
					position: absolute;
					right: 31%;
				}
			}
		}

		.files_box {
			flex: 1;

			.top_funs {
				height: 80px;
				padding: 0 20px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1px solid #e3e3e3;

				.funs_left {
					display: flex;
					align-items: center;

					span {
						margin-left: 50px;
					}

					/* 精确匹配：当元素没有行内的pointer-events: not-allowed时生效 */
					span:hover:not([style*="cursor: not-allowed"]) {
						color: #6cb8ff !important;
					}

					/* 更严谨的写法：同时排除可能的空格差异 */
					span:hover:not([style*="cursor:not-allowed"]):not([style*="cursor: not-allowed"]) {
						color: #6cb8ff !important;
					}

				}
			}

			.files_list_box {
				display: flex;
				// padding: 20px;

				div {
					width: 100px;
					min-width: 100px;
					max-width: 100px;
					padding: 10px;
					cursor: pointer;
					position: relative;
					flex: 1;

					.top_check {
						position: absolute;
						top: -8px;
						left: 24px;
					}
				}
			}
		}
	}
</style>